﻿using Microsoft.AspNet.Identity;
using Sidvall.IdentityManager.Data;
using Sidvall.IdentityManager.Security.Entities;
using System;
using System.Threading.Tasks;

namespace Sidvall.IdentityManager.Security
{
    public class EmailTokenProvider : UserTokenProvider
    {
        private string _Subject;
        public string Subject
        {
            get { return _Subject ?? string.Empty; }
            set { _Subject = value; }
        }

        private string _BodyFormat;
        public string BodyFormat
        {
            get { return _BodyFormat ?? "{0}"; }
            set { _BodyFormat = value; }
        }

        public override Task<bool> IsValidProviderForUserAsync(UserManager<AspNetUsers, string> manager, AspNetUsers user)
        {
            var isValid = !string.IsNullOrWhiteSpace(user.Email) && user.EmailConfirmed;
            return Task.FromResult(isValid);
        }

        protected override string GetUserModifier(string purpose, IAspNetUsers user)
        {
            return "Email:" + purpose + ":" + user.Email;
        }

        public override Task NotifyAsync(string token, UserManager<AspNetUsers, string> manager, AspNetUsers user)
        {
            if (manager == null)
                throw new ArgumentNullException(nameof(manager));
            return manager.SendEmailAsync(user.Id, this.Subject, String.Format(System.Globalization.CultureInfo.CurrentCulture, this.BodyFormat, token));
        }
    }
}
